package com.frogs.ucenter.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.TaskActionStatusEnum;
import com.frogs.ucenter.entity.SubFlowInfo;
import com.frogs.ucenter.entity.SubFlowTaskRelation;
import com.frogs.ucenter.entity.TaskInfo;
import com.frogs.ucenter.entity.TaskInfoExt;
import com.frogs.ucenter.service.ActionInfoService;
import com.frogs.ucenter.service.SubFlowInfoService;
import com.frogs.ucenter.service.TaskInfoService;

@Controller
@RequestMapping("/admin/taskInfo")
public class TaskInfoController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/taskInfo";

    private static final String HOME_VIEW = "admin/taskInfo/home";

    private static final String EDIT_VIEW = "admin/taskInfo/edit";
    private static final String LIST_VIEW = "admin/taskInfo/list";
    
    private static final String PROMOTION_LIST = "/promotionList";
    
    private static final String PROMOTION_LIST_VIEW = "admin/taskInfo/promotionList";
    
    private static final String RED_PACK_LIST = "/redPackList";
    
    private static final String RED_PACK_LIST_VIEW = "admin/taskInfo/redPackList";
    
    private static final String LIST_RELATION = "/listRelation";
    private static final String LIST_RELATION_VIEW = ROOT_VIEW + LIST_RELATION;
    private static final String EDIT_RELATION = "/editRelation";
    private static final String EDIT_RELATION_VIEW = ROOT_VIEW + EDIT_RELATION;
    private static final String ADD_RELATION = "/addRelation";
    private static final String DELETE_RELATION = "/deleteRelation";

    @Resource
    private TaskInfoService taskInfoService;
    
    @Resource
    private ActionInfoService actionInfoService;
    
    @Resource
    private SubFlowInfoService subFlowInfoService;
    
    @RequestMapping()
    public String listTaskInfo(HttpServletRequest request, ModelMap model, String isLookup) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        getPageList( model );
        if (StringUtil.isEmpty(isLookup)) {
        	return HOME_VIEW;
        }
        else{
        	return LIST_VIEW;
        }
    }
    
    @RequestMapping(DELETE_RELATION)
    public String deleteRelation(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestParam(required=true, value="ids") String inIdList) {
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        boolean flag = true;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            taskInfoService.deleteRelation( model ); 
            builder = DWZResponse.getSucessBuilder("删除成功");
        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("删除失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        request.setAttribute("flag", flag);
        return null;
    }

    @RequestMapping(ADD_RELATION)
    public String addSubFlowInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model,SubFlowTaskRelation subFlowTaskRelation) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        DWZResponse.Builder builder;
        boolean flag = true;
        try {
        	int subFlowId = subFlowTaskRelation.getSubFlowId();
        	int sequence = subFlowTaskRelation.getSequence();
        	if(taskInfoService.isExistsTaskRelation(subFlowId, sequence)){
        		flag = false;
        		builder = DWZResponse.getFailBuilder("新增失败,已经存在该序号，请重新输入序号");
        	}else{
            	taskInfoService.insertRelation( subFlowTaskRelation); 
                builder = DWZResponse.getSucessBuilder("新增成功");
        	}
        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("新增失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        request.setAttribute("flag", flag);
        return null;
    }
    
    @RequestMapping(LIST_RELATION)
    public String listSubFlowInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        List<TaskInfoExt> taskInfoList = taskInfoService.getTaskInfoExtList( model); 
        SubFlowInfo subFlowInfo = subFlowInfoService.getById(Integer.valueOf(model.get("eqSubFlowId").toString()));
        model.put("taskInfoList",taskInfoList);
        model.put("subFlowInfo",subFlowInfo);
        model.put("actionList", actionInfoService.getList(new HashMap<String,Object>(), 0, 100));
        return LIST_RELATION_VIEW;
    }
    
    @RequestMapping(EDIT_RELATION)
    public String editRelation(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "eqSubFlowId", -1 );
        model.put( "model",subFlowInfoService.getById( id ) ); 
        return EDIT_RELATION_VIEW;
    }

    @RequestMapping(EDIT)
    public String createTaskInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Map<String,Object> param = new HashMap<String,Object>();
       
        if( id > 0 ){
            model.put( "model",taskInfoService.getById( id ) ); 
        }else{
        	param.put("eqStatus", TaskActionStatusEnum.ENABLED.getId());//新增的时候不能取没启用的动作
        }
        model.put("actionList", actionInfoService.getList(new HashMap<String,Object>(), 0, 100));
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveTaskInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, TaskInfo taskInfo) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        boolean flag = true;
        try {
            taskInfoService.insert( taskInfo ); 
            builder = DWZResponse.getSucessBuilder("新增成功");
        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("新增失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        request.setAttribute("flag", flag);
        return null;
    }

    @RequestMapping(SHOW)
    public String showTaskInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( taskInfoService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateTaskInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, TaskInfo taskInfoNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        boolean flag = true;
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                TaskInfo taskInfo = taskInfoService.getById( id ); 
                PropertyUtils.copyProperties(taskInfo, taskInfoNew);
                taskInfoService.update( taskInfo ); 
                model.clear();
                builder = DWZResponse.getSucessBuilder("更新成功");
            } catch (Exception e) {
            	flag = false;
                builder = DWZResponse.getFailBuilder("更新失败" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        request.setAttribute("flag", flag);
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteTaskInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestParam(required=true, value="ids") String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        boolean flag = true;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            TaskInfo taskInfo = taskInfoService.getById(Integer.parseInt(idArray[0]));
            int status = taskInfo.getStatus();
            Date endDate = taskInfo.getEndTime();
            if(status == TaskActionStatusEnum.UNABLE.getId() || endDate.before(new Date())){
                taskInfoService.delete( model ); 
                builder = DWZResponse.getSucessBuilder("删除成功");
            }else{
            	flag = false;
            	builder = DWZResponse.getFailBuilder("删除失败,只有未启用或是过期的任务才可以删除,如有疑问,请联系开发人员");
            }

        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("删除失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        request.setAttribute("flag", flag);
        return null;
    }

    private PageList<TaskInfo> getPageList(ModelMap model) {
        PageList<TaskInfo> taskInfoList = taskInfoService.getList( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        Map<String,Object> param = new HashMap<String,Object>();
        model.put("actionList", actionInfoService.getList(param, 0, 100));
        model.put("taskInfoList",taskInfoList);
        model.put("pageTurn",taskInfoList.getPageTurn());
        return taskInfoList;
    }
    
    @RequestMapping(PROMOTION_LIST)
    public String getPromotionList(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        int sendCardType = reqInfo.getIntParameter("sendCardType", 0);//卡券发放类型
        int pageNum = reqInfo.getIntParameter("pageNum", 0);
        int numPerPage = reqInfo.getIntParameter("numPerPage", 1000);
        model.put("promotionList", taskInfoService.getPromotionList(sendCardType, pageNum, numPerPage));
        setRequestModelMap(request, model);
        return PROMOTION_LIST_VIEW;
    }
    
    @RequestMapping(RED_PACK_LIST)
    public String getRedPackList(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        int pageNum = reqInfo.getIntParameter("pageNum", 0);
        int numPerPage = reqInfo.getIntParameter("numPerPage", 1000);
        model.put("redPackList", taskInfoService.getRedPackList(pageNum, numPerPage));
        setRequestModelMap(request, model);
        return RED_PACK_LIST_VIEW;
    }
}